package com.vsd.service.impl;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.demo.util.JSONUtils;
import com.demo.util.MathUtil;
import com.demo.util.ProperityUtil;
import com.demo.util.SqlUtils;
import com.demo.util.StringUtil;
import com.shopcart.domain.Store;
import com.vsd.repository.StoreRepository;
import com.vsd.repository.UserCollectionRepository;
import com.vsd.service.CodeService;
import com.vsd.service.StoreService;
import com.zy.store.proto.MOAppStore.MStore;
import com.zy.store.proto.MOAppStore.MStoreMini;
import com.zy.store.proto.MOAppStore.MStoreMiniList;

/**
 * 用户服务接口实现
 * 
 * @author jiekechoo
 *
 */
@Service
@Transactional
public class StoreServiceImpl implements StoreService {
	@SuppressWarnings("unused")
	private static final Logger LOGGER = LoggerFactory
			.getLogger(StoreServiceImpl.class);
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Autowired
	private  StoreRepository storeRepository;
	
	@Autowired
	private UserCollectionRepository userCollectionRepository;
	
	@Autowired
	private CodeService codeService;

	@Autowired
	private Environment env;
	@Autowired
	private ProperityUtil properityUtil;

	@Override
	public Collection<Store> findAll() {
		return storeRepository.findAll();
	}
	
	@Override
	public int update(Store s) throws Exception {
		String sql = SqlUtils.update(s, true, " where id = '"+s.getId()+"'");
		return jdbcTemplate.update(sql);
	}
	
	@Override
	public Store  save(Store store) {
		return storeRepository.save(store);
	}
	
	@Override
	public Page<Store> findAll(Pageable p) {
		return storeRepository.findAll(p);
	}
	
	@Override
	public Page<Store> findByNameLike(String name,Pageable p) {
		return storeRepository.findByNameLike(name, p);
	}

	@Override
	public Store findByAccountAndPassword(String account, String password) {
		// TODO Auto-generated method stub
		return storeRepository.findByAccountAndPassword(account, password);
	}

	@Override
	public Page<Store> findByPhone(String phone,Pageable p) {
		// TODO Auto-generated method stub
		return storeRepository.findByPhone(phone,p);
	}

	@Override
	public Page<Store> findByIdIn(List<String> ids, Pageable p) {
		// TODO Auto-generated method stub
		return storeRepository.findByIdIn(ids, p);
	}

	@Override
	public Store findById(String id) {
		// TODO Auto-generated method stub
		return storeRepository.findOne(id);
	}

	@Override
	public MStore.Builder findStoreDetail(String id,String userId) {
		MStore.Builder ret = MStore.newBuilder();
		String sql ="select s.*,sc.`name` as cateName,ci.`name` as cityName "
				+ ",(select count(1) from s_store_comment sc1 where sc1.store_id = s.id) as commentCnt"
				+ ",(select avg(sc1.score) from s_store_comment sc1 where sc1.store_id = s.id ) as avgScore	"
				+ "from s_store s	left join s_store_category sc on s.cate_code = sc.`code`	"
				+ "left join f_city ci on s.area_code = ci.`code`	where s.id='"+id+"' and s.is_online = 1  and s.closed=0 ORDER BY s.sort desc ";
		
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		if(maps==null||maps.size()==0) return ret;
		Map<String, Object> map = maps.get(0);
		ret.setAddress(StringUtil.obj2String(map.get("address")));
		ret.setCateName(StringUtil.obj2String(map.get("cateName")));
		ret.setCityName(StringUtil.obj2String(map.get("cityName")));
		ret.setCommentCnt(MathUtil.formatAsComment(StringUtil.obj2String(map.get("commentCnt"))));
		ret.setStar(map.get("avgScore")==null?0:new Double(StringUtil.obj2String(map.get("avgScore"))));
		ret.setPhone(StringUtil.obj2String(map.get("phone")));
		ret.setLat(StringUtil.obj2String(map.get("lat")));
		ret.setLng(StringUtil.obj2String(map.get("lng")));
		ret.setShareMsg(properityUtil.getSelf_url()+"/m/store/"+id);
		String rate = StringUtil.obj2String(map.get("wine_rate"));
		ret.setRate(StringUtils.isBlank(rate)?codeService.getWineRate():rate);
		ret.setLogo(StringUtil.obj2String(map.get("logo")));
		ret.setName(StringUtil.obj2String(map.get("name")));
		String imgs = StringUtil.obj2String(map.get("imgs"));
		ret.setInfo(StringUtil.obj2String(map.get("info")));
		List<String> imgArr = Arrays.asList(imgs.split(","));
		for (String str : imgArr) {
			ret.addImgs(str);
		}
		ret.setIsCollect(0);
		
		//是否收藏
		if(StringUtils.isNoneBlank(userId)){
			int c = userCollectionRepository.isCollect(userId, 2, id);
			if(c>0) ret.setIsCollect(1);
		}
		return ret;
	}
	
	//排序 1智能排序 2 评分 3距离 4人均（默认1）
	@Override
	public MStoreMiniList.Builder selectAppList(String cateCode,String key, String areaCode, String lat,
			String lng, Integer page, Integer limit,Integer sort) {
		// TODO Auto-generated method stub
		String sql = "select s.*,sc.`name` as cateName,ci.`name` as cityName";
		if(StringUtils.isNotBlank(lat)&&StringUtils.isNotBlank(lng)){
			sql+=",getDistance(s.lng,s.lat,"+lng+","+lat+") as distance";
		}
				
		sql+= ",(select count(1) from s_store_comment sc where sc.store_id=s.id) as commentCnt"
			+ ",(select AVG(score) from s_store_comment sco where sco.store_id=s.id) as avgScore "
			+ "from s_store s	left join s_store_category sc on sc.`code` = s.cate_code 	"
			+ "left join f_city ci on ci.`code` = s.area_code	where s.is_online = 1 and s.closed=0";
		
		if(StringUtils.isNotBlank(cateCode)){
			sql +=" and s.cate_code like '%"+cateCode+"%'";
		}
		if(StringUtils.isNotBlank(key)){
			sql +=" and s.name like '%"+key+"%'";
		}
		if(StringUtils.isNotBlank(areaCode)){
			sql +=" and s.area_code like '%"+areaCode+"%'";
		}
		switch (sort) {
		case 1:
			if(StringUtils.isNotBlank(lng)){
				sql+=" order by distance desc";
			}else{
				sql+="order by s.sort desc,avgScore desc";
			}
			break;
		case 2:
			sql+="order by avgScore desc,s.sort desc";
			break;
		case 3:
			if(StringUtils.isNotBlank(lng)){
				sql+=" order by distance desc";
			}else{
				sql+="order by s.sort desc,avgScore desc";
			}
			break;
		case 4:
			sql+=" order by s.avg_price desc";
			break;
		default:
			break;
		}
		if(page!=null){
			sql+=" limit "+(page*limit)+","+limit;
		}
		
		MStoreMiniList.Builder ret = MStoreMiniList.newBuilder();
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		for (Map<String, Object> map : maps) {
			MStoreMini.Builder m = MStoreMini.newBuilder();
			m.setCateName(StringUtil.obj2String(map.get("cateName")));
			m.setCityName(StringUtil.obj2String(map.get("cityName")));
			m.setCommentCnt(MathUtil.formatAsComment(StringUtil.obj2String(map.get("commentCnt"))));
			m.setStar(map.get("avgScore")==null?0:new Double(StringUtil.obj2String(map.get("avgScore"))));
			m.setLogo(StringUtil.obj2String(map.get("logo")));
			m.setTitle(StringUtil.obj2String(map.get("name")));
			m.setDistance(MathUtil.getDistanceStr(StringUtil.obj2String(map.get("distance"))));
			m.setId(StringUtil.obj2String(map.get("id")));
			ret.addList(m);
		}
		
		return ret;
	}

	@Override
	public Page<Store> findAreaCode(String areaCode, Pageable p) {
		// TODO Auto-generated method stub
		return storeRepository.findByAreaCodeLike(areaCode+"%", p);
	}

	@Override
	public Page<Store> findAreaCodeAndNameLike(String areaCode, String name,
			Pageable p) {
		// TODO Auto-generated method stub
		return storeRepository.findByAreaCodeLikeAndNameLike(areaCode+"%", "%"+name+"%", p);
	}
	@Override
	public String findStore(String id, String userId){
		String sql ="select s.*,sc.`name` as cateName,ci.`name` as cityName "
				+ ",(select count(1) from s_store_comment sc where sc.store_id = s.id) as commentCnt"
				+ ",(select avg(sc1.score) from s_store_comment sc1 where sc1.store_id = s.id ) as avgScore	"
				+ "from s_store s	left join s_store_category sc on s.cate_code = sc.`code`	"
				+ "left join f_city ci on s.area_code = ci.`code`	where s.id='"+id+"' and s.is_online = 1  and s.closed=0 ORDER BY s.sort desc ";
		
		Map<String, Object> map = jdbcTemplate.queryForMap(sql);
		String imgs = StringUtil.obj2String(map.get("imgs"));
		map.put("images", imgs.split(","));
		map.put("firstImg", imgs.split(",")[0]);
		map.put("isCollect", 0);
		//是否收藏
		if(StringUtils.isNoneBlank(userId)){
			int c = userCollectionRepository.isCollect(userId, 2, id);
			if(c>0) map.put("isCollect", 1);
		}
		return JSONUtils.serialize(map);
	}
	@Override
	public String selectList(String cateCode, String areaCode, String lat,
			String lng, Integer page, Integer limit){
		String sql = "select s.*,sc.`name` as cateName,ci.`name` as cityName";
		if(StringUtils.isNoneBlank(lat)&&StringUtils.isNoneBlank(lng)){
			sql+=",getDistance(s.lng,s.lat,"+lng+","+lat+") as distance";
		}
				
		sql+= ",(select count(1) from s_store_comment sc where sc.store_id=s.id) as commentCnt"
			+ ",(select AVG(score) from s_store_comment sco where sco.store_id=s.id) as avgScore "
			+ "from s_store s	left join s_store_category sc on sc.`code` = s.cate_code 	"
			+ "left join f_city ci on ci.`code` = s.area_code	where s.is_online = 1 and s.closed=0";
		
		if(StringUtils.isNoneBlank(cateCode)){
			sql +=" and s.cate_code like '%"+cateCode+"%'";
		}
		if(StringUtils.isNoneBlank(areaCode)){
			sql +=" and s.area_code like '%"+areaCode+"%'";
		}
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		return JSONUtils.serialize(maps);
	}
}
